﻿using HalconDotNet;
using MotionControl;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using UserControlHelper;
using WHW_NetUtility;
using XXTUserUI;

namespace MainFrame
{
    public partial class FormConfig : Form
    {
        public FormConfig()
        {
            InitializeComponent();
          
        }
        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_save_config_Click(object sender, EventArgs e)
        {
            if (GlobalVar.userConfig == null)
                GlobalVar.userConfig = new ConfigData();
            #region 上层输送模块
        
            GlobalVar.userConfig.isEnableUpSignal = ckb_IsEnableUpSignal.Checked;
            GlobalVar.userConfig.isEnableDownSignal = ckb_IsEnableDownSignal.Checked;
            GlobalVar.userConfig.NG_distance = (double)nud_NG_distance.Value;
            #endregion
            #region 相机模块
            GlobalVar.userConfig.CameraSN_pos = tbx_CameraSn_Pos.Text;
            GlobalVar.userConfig.CameraSN_draw = tbx_CameraSn_Draw.Text;
            GlobalVar.userConfig.CameraSN_check = tbx_CameraSn_Check.Text;
            if (GlobalVar.userConfig.PlateVisionList == null)
            {
                GlobalVar.userConfig.PlateVisionList = new List<PlateVisionInfo>();
                for(int i=0;i< plateCount; i++)
                {
                    GlobalVar.userConfig.PlateVisionList.Add(new PlateVisionInfo());
                }
            }
            if(GlobalVar.userConfig.PlateVisionList.Count< plateCount)
            {
                for (int i = GlobalVar.userConfig.PlateVisionList.Count; i <plateCount; i++)
                {
                    GlobalVar.userConfig.PlateVisionList.Add(new PlateVisionInfo());
                }
            }
            var curPlat = GetCurrentSelet();
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].Sn = tbx_CameraSn.Text;
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].CailList = GetCailPoint();
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].CenterRealX =(double) nud_CenterXplate.Value;
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].CenterRealY = (double)nud_CenterYplate.Value;
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].Xmax = (double)nud_Xmax.Value;
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].Xmin = (double)nud_Xmin.Value;
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].Ymin = (double)nud_Ymin.Value;
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].Ymax = (double)nud_Ymax.Value;
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].Rmin = (double)nud_Rmin.Value;
            GlobalVar.userConfig.PlateVisionList[(int)curPlat].Rmax = (double)nud_Rmax.Value;
            GlobalVar.userConfig.delayCamera = (int)nud_delayCamera.Value;
            #endregion
            #region 数据库操作
            GlobalVar.userConfig.db_IP = tbx_db_IP.Text;
            GlobalVar.userConfig.db_UserName = tbx_db_UserName.Text;
            GlobalVar.userConfig.db_Name = tbx_db_Name.Text;
            GlobalVar.userConfig.db_Password = tbx_db_Password.Text;
            GlobalVar.userConfig.db_T_Alarm = tbx_db_T_AlarmInfo.Text;
            GlobalVar.userConfig.db_T_Product = tbx_db_T_Product.Text;
            GlobalVar.userConfig.db_T_Status = tbx_db_T_MachineStatus.Text;
            #endregion
            GlobalVar.userConfig.airCutTime = (int)nud_airCutTime.Value;
            GlobalVar.userConfig.DelayCheck_Down = (int)nud_DownDelayCheck.Value;
            GlobalVar.userConfig.isCutFinishOK = ckb_IsCutFinishOK.Checked;
            GlobalVar.userConfig.CutKeepTime = (int)nud_cutKeepTime.Value;
            GlobalVar.userConfig.LabelKeepAirTime = (int)nud_LabelKeepAirTime.Value;
            #region 贴标模块
            GlobalVar.userConfig.IsAutoFly = ckb_IsAutoFly.Checked;
            GlobalVar.userConfig.isEnableVisionsyr = ckb_MaualScan.Checked;
            GlobalVar.userConfig.downProTime_In = (int)nud_DownCheckPro.Value;
            GlobalVar.userConfig.clampTime = (int)nud_ClampTime.Value;
            GlobalVar.userConfig.airTime = (int)nud_airTime.Value;
            GlobalVar.userConfig.IsLabelResultOk = ckb_IsLabelResultOk.Checked;
            GlobalVar.userConfig.IsWordOk = ckb_IsWordOk.Checked;
            GlobalVar.userConfig.isPosOk = ckb_IsPosOk.Checked;
            GlobalVar.userConfig.IsGetLabelTwo = ckb_IsGetLabelTwo.Checked;
            GlobalVar.userConfig.CameraNGTime =(int) nud_cameraNGTimes.Value;
            GlobalVar.userConfig.getLabelNGTimes = (int)nud_getLabelNGTimes.Value;
            GlobalVar.userConfig.getFlyNGTimes = (int)nud_flyLabelNGTimes.Value;

            GlobalVar.userConfig.IsGetLabelOK = ckb_IsGetLabelOK.Checked;
            GlobalVar.userConfig.airRepeatTime = (int)nud_airRepeatTime.Value;
            GlobalVar.userConfig.airInterval = (int)nud_airIntervel.Value;

            GlobalVar.userConfig.isLabelFinishOK = ckb_IsLabelFinishOK.Checked;
            GlobalVar.userConfig.IsPosAfterLabel = ckb_IsPosAfterLabel.Checked;
            GlobalVar.userConfig.IsCheckCutResult = ckb_IsCheckCutResult.Checked;
   
            #endregion
            #region 数据上传
            if (GlobalVar.userConfig.UploadInfo == null)
                GlobalVar.userConfig.UploadInfo = new UrlInfo();
            GlobalVar.userConfig.UploadInfo.DevCode = tbx_DevCode.Text.Trim();
            GlobalVar.userConfig.UploadInfo.IsUploadTcp = ckb_EnableTcp.Checked;
            GlobalVar.userConfig.UploadInfo.IsUploadUrl = ckb_EnableUrl.Checked;
            GlobalVar.userConfig.UploadInfo.url_AlarmUpload = tbx_url_Alarm.Text;
            GlobalVar.userConfig.UploadInfo.url_CheckUpload = tbx_url_Check.Text;
            GlobalVar.userConfig.UploadInfo.url_DataUpload = tbx_url_Data.Text;
            GlobalVar.userConfig.UploadInfo.url_GetDate = tbx_url_GetDate.Text;
            GlobalVar.userConfig.UploadInfo.url_GetModelInfo = tbx_url_GetModelInfo.Text;
            GlobalVar.userConfig.UploadInfo.url_DevStatusHead = tbx_url_DevStatusHead.Text;
            GlobalVar.userConfig.UploadInfo.url_DeviceName = tbx_DeviceName.Text;

            GlobalVar.userConfig.cmdList = GetCmdList();
            uTCPIP2.SaveParameter();
            #endregion
            SerializeHelper.serializeFile(GlobalVar.configPath, GlobalVar.userConfig, "软件配置");
            
        }
        /// <summary>
        /// 获取当前选中的平台与相机
        /// </summary>
        /// <returns></returns>
        private e_CameraPlate GetCurrentSelet()
        {
            var e_cur = e_CameraPlate.定位相机平台1;
            if (rbn_ScanCamera.Checked)
            {
                if (rbn_plate1.Checked)
                    e_cur= e_CameraPlate.图案相机平台1;
                else if(rbn_plate2.Checked)
                    e_cur = e_CameraPlate.图案相机平台2;
            }
            else if (rbn_posCamera.Checked)
            {
                if (rbn_plate1.Checked)
                    e_cur = e_CameraPlate.定位相机平台1;
                else if (rbn_plate2.Checked)
                    e_cur = e_CameraPlate.定位相机平台2;
            }
            else if (rbn_CheckCamera.Checked)
            {
                if (rbn_plate1.Checked)
                    e_cur = e_CameraPlate.检测相机平台1;
                else if (rbn_plate2.Checked)
                    e_cur = e_CameraPlate.检测相机平台2;
            }
            return e_cur;
        }
        private List<CalibPoint> GetCailPoint()
        {
            try
            {
                var CailList = new List<CalibPoint>();
                for (int i = 0; i < dgv_camera_calib.Rows.Count; i++)
                {
                    var curCailPoint = new CalibPoint();
                    curCailPoint.Index = Convert.ToInt32(dgv_camera_calib.Rows[i].Cells["dgvc_index"].Value);
                    curCailPoint.pixX = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells["dgvc_pixX"].Value);
                    curCailPoint.pixY = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells["dgvc_pixY"].Value);
                    curCailPoint.realX = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells["dgvc_realX"].Value);
                    curCailPoint.realY = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells["dgvc_realY"].Value);
                    curCailPoint.realR= Convert.ToSingle(dgv_camera_calib.Rows[i].Cells["dgvc_realR"].Value);
                    CailList.Add(curCailPoint);
                }
                return CailList;
            }
            catch(Exception ex)
            {
                return null;
            }
           
        }
        private List<Cmd> GetCmdList()
        {
            try
            {
                var CailList = new List<Cmd>();
                for (int i = 0; i < dgv_cmd.Rows.Count; i++)
                {
                    var curCmd = new Cmd();
                    curCmd.action = Convert.ToString(dgv_cmd.Rows[i].Cells["dgvc_action"].Value);
                    curCmd.cmd = Convert.ToString(dgv_cmd.Rows[i].Cells["dgvc_msg"].Value);
                    CailList.Add(curCmd);
                }
                return CailList;
            }
            catch (Exception ex)
            {
                return null;
            }

        }

        private void btn_calibrate_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgv_camera_calib.Rows == null || dgv_camera_calib.Rows.Count < 4)
                {
                    MessageBox.Show("标定数据太少，请准备至少9个点数据");
                    return;
                }
                if (DialogResult.No == MessageBox.Show($"确定要{((Button)sender).Text}吗?", "询问", MessageBoxButtons.YesNo))
                    return;
                #region 取表格数据
                List<PointF> calibrate_RealPoint = new List<PointF>();
                List<PointF> calibrate_PixPoint = new List<PointF>();
                List<PointF> rotate_RealPoint = new List<PointF>();
                List<PointF> rotate_PixPoint = new List<PointF>();
                PointF actPoint = new PointF() { X = 0, Y = 0 };
                for (int i = 0; i < dgv_camera_calib.Rows.Count; i++)
                {
                    if (dgv_camera_calib.Rows[i].Cells[1].Value != null && dgv_camera_calib.Rows[i].Cells[2].Value != null)
                    {
                        var curX = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells[1].Value);
                        var curY = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells[2].Value);
                        if (i < 9)
                            calibrate_PixPoint.Add(new PointF() { X = Convert.ToSingle(curX), Y = Convert.ToSingle(curY) });
                        else
                            rotate_PixPoint.Add(new PointF() { X = Convert.ToSingle(curX), Y = Convert.ToSingle(curY) });
                    }
                }
                for (int i = 0; i < dgv_camera_calib.Rows.Count; i++)
                {
                    if (dgv_camera_calib.Rows[i].Cells[3].Value != null && dgv_camera_calib.Rows[i].Cells[4].Value != null)
                    {
                        var curX = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells[3].Value);
                        var curY = Convert.ToSingle(dgv_camera_calib.Rows[i].Cells[4].Value);
                        if (i < 9)
                            calibrate_RealPoint.Add(new PointF() { X = Convert.ToSingle(curX), Y = Convert.ToSingle(curY) });
                        else
                        {
                            rotate_RealPoint.Add(new PointF() { X = Convert.ToSingle(curX), Y = Convert.ToSingle(curY) });
                            actPoint = new PointF()
                            {
                                X = Convert.ToSingle(curX),
                                Y = Convert.ToSingle(curY)
                            };
                        }
                    }
                }
                #endregion
                var curCamera = GetCurrentSelet();
                #region 九点标定+旋转标定
                var caildata = visionProc.CalibratePlate(calibrate_PixPoint, calibrate_RealPoint);
                if (caildata != null && caildata.Type != HTupleType.EMPTY && caildata.DArr.Length > 0)
                {
                    tempCail = caildata;
                    var cailpixdata = visionProc.CalibratePlate(calibrate_RealPoint,calibrate_PixPoint);
                   
                    HOperatorSet.HomMat2dToAffinePar(tempCail,out HTuple sx, out HTuple sy, out HTuple phi, out HTuple theta, out HTuple tx, out HTuple ty);
                    displalyInfo.displayInfoMain(JsonConvert.SerializeObject(caildata.DArr)+ $"sx{sx.D}" + $"sy{sy.D}" + $"phi{phi.D}" + $"theta{theta.D}"+ $"tx{tx.D}"+ $"ty{ty.D}");
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].arr_cail = caildata.DArr;
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].arr_pixcail = cailpixdata.DArr;
                    var Point_realRorate =visionProc.CalibrateRotateCenter(GlobalVar.userConfig.PlateVisionList[(int)curCamera].arr_cail, rotate_PixPoint, actPoint);
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].CenterRealX = Point_realRorate.X;
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].CenterRealY = Point_realRorate.Y;
                    if (rotate_RealPoint.Count > 0)
                    {
                        GlobalVar.userConfig.PlateVisionList[(int)curCamera].CailPointX = rotate_RealPoint[0].X;
                        GlobalVar.userConfig.PlateVisionList[(int)curCamera].CailPointY = rotate_RealPoint[0].Y;
                    }
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].rorateOffsetX = (double)visionProc.RorateOffset.X;
                    GlobalVar.userConfig.PlateVisionList[(int)curCamera].rorateOffsetY = (double)visionProc.RorateOffset.Y;
                    nud_CenterXplate.Value = (decimal)GlobalVar.userConfig.PlateVisionList[(int)curCamera].CenterRealX;
                    nud_CenterYplate.Value = (decimal)GlobalVar.userConfig.PlateVisionList[(int)curCamera].CenterRealY;
                    nud_Xmax.Value = (decimal)GlobalVar.userConfig.PlateVisionList[(int)curCamera].Xmax;
                    nud_Xmin.Value = (decimal)GlobalVar.userConfig.PlateVisionList[(int)curCamera].Xmin;
                    nud_Ymax.Value = (decimal)GlobalVar.userConfig.PlateVisionList[(int)curCamera].Ymax;
                    nud_Ymin.Value = (decimal)GlobalVar.userConfig.PlateVisionList[(int)curCamera].Ymin;
                    nud_Rmax.Value = (decimal)GlobalVar.userConfig.PlateVisionList[(int)curCamera].Rmax;
                    nud_Rmin.Value = (decimal)GlobalVar.userConfig.PlateVisionList[(int)curCamera].Rmin;
                    
                }
                #endregion
            }
            catch (Exception ex)
            {
                Log4Helper.WriteLog(ex);
            }
        }

        private HTuple tempCail = new HTuple();

        private int plateCount = 6;
      /// <summary>
      /// 将配置显示到控件上
      /// </summary>
        private void PameraToControl()
        {
            #region 上层输送模块
      
            ckb_IsEnableUpSignal.Checked = GlobalVar.userConfig.isEnableUpSignal;
            ckb_IsEnableDownSignal.Checked = GlobalVar.userConfig.isEnableDownSignal;
            nud_NG_distance.Value = (decimal)GlobalVar.userConfig.NG_distance;
            #endregion
            #region 相机模块
            tbx_CameraSn_Pos.Text = GlobalVar.userConfig.CameraSN_pos;
            tbx_CameraSn_Draw.Text = GlobalVar.userConfig.CameraSN_draw;
            tbx_CameraSn_Check.Text = GlobalVar.userConfig.CameraSN_check;
            rbn_posCamera.Checked = true;
            rbn_ScanCamera.Checked = false;
            rbn_plate1.Checked = true;
            rbn_plate2.Checked = false;
            if (GlobalVar.userConfig.PlateVisionList == null)
            {
                GlobalVar.userConfig.PlateVisionList = new List<PlateVisionInfo>();
                plateCount = Enum.GetNames(typeof(e_CameraPlate)).Length;
                for (int i = 0; i < plateCount; i++)
                {
                    GlobalVar.userConfig.PlateVisionList.Add(new PlateVisionInfo());
                }
            }
            var curPlate = GetCurrentSelet();
            tbx_CameraSn.Text = GlobalVar.userConfig.PlateVisionList[(int)curPlate].Sn;
            if (GlobalVar.userConfig.PlateVisionList[(int)curPlate].CailList!=null)
            {
                CailPointToTable(GlobalVar.userConfig.PlateVisionList[(int)curPlate].CailList);
            }
            nud_delayCamera.Value = GlobalVar.userConfig.delayCamera;
            nud_cameraNGTimes.Value = GlobalVar.userConfig.CameraNGTime;
            nud_getLabelNGTimes.Value = GlobalVar.userConfig.getLabelNGTimes;
            #endregion
            #region 数据库操作
            tbx_db_IP.Text = GlobalVar.userConfig.db_IP;
            tbx_db_UserName.Text = GlobalVar.userConfig.db_UserName;
            tbx_db_Name.Text = GlobalVar.userConfig.db_Name;
            tbx_db_Password.Text = GlobalVar.userConfig.db_Password;
            tbx_db_T_AlarmInfo.Text = GlobalVar.userConfig.db_T_Alarm;
            tbx_db_T_Product.Text = GlobalVar.userConfig.db_T_Product;
            tbx_db_T_MachineStatus.Text = GlobalVar.userConfig.db_T_Status;
            #endregion
            ckb_IsCutFinishOK.Checked = GlobalVar.userConfig.isCutFinishOK;
            nud_airCutTime.Value = GlobalVar.userConfig.airCutTime;
            nud_cutKeepTime.Value = GlobalVar.userConfig.CutKeepTime;
            nud_LabelKeepAirTime.Value = GlobalVar.userConfig.LabelKeepAirTime;
            #region 贴标模块
            ckb_MaualScan.Checked = GlobalVar.userConfig.isEnableVisionsyr;
            ckb_IsAutoFly.Checked = GlobalVar.userConfig.IsAutoFly;
            nud_ClampTime.Value = GlobalVar.userConfig.clampTime;
            nud_airTime.Value = GlobalVar.userConfig.airTime;
            nud_flyLabelNGTimes.Value = GlobalVar.userConfig.getFlyNGTimes;

            nud_DownCheckPro.Value = GlobalVar.userConfig.downProTime_In;
            ckb_IsPosOk.Checked = GlobalVar.userConfig.isPosOk;
            ckb_IsWordOk.Checked = GlobalVar.userConfig.IsWordOk;
            ckb_IsLabelResultOk.Checked = GlobalVar.userConfig.IsLabelResultOk;
            ckb_IsGetLabelTwo.Checked = GlobalVar.userConfig.IsGetLabelTwo;

            ckb_IsGetLabelOK.Checked = GlobalVar.userConfig.IsGetLabelOK;

            nud_airRepeatTime.Value = GlobalVar.userConfig.airRepeatTime;
            nud_airIntervel.Value = GlobalVar.userConfig.airInterval;

            ckb_IsLabelFinishOK.Checked = GlobalVar.userConfig.isLabelFinishOK;
            ckb_IsPosAfterLabel.Checked = GlobalVar.userConfig.IsPosAfterLabel;
            ckb_IsCheckCutResult.Checked= GlobalVar.userConfig.IsCheckCutResult;
            #endregion
            nud_DownDelayCheck.Value = GlobalVar.userConfig.DelayCheck_Down;
            #region 数据上传
            if (GlobalVar.userConfig.UploadInfo == null)
                GlobalVar.userConfig.UploadInfo = new UrlInfo();
            tbx_DevCode.Text = GlobalVar.userConfig.UploadInfo.DevCode;
            ckb_EnableTcp.Checked = GlobalVar.userConfig.UploadInfo.IsUploadTcp;
            ckb_EnableUrl.Checked = GlobalVar.userConfig.UploadInfo.IsUploadUrl;
            tbx_url_Alarm.Text = GlobalVar.userConfig.UploadInfo.url_AlarmUpload;
            tbx_url_Check.Text = GlobalVar.userConfig.UploadInfo.url_CheckUpload;
            tbx_url_Data.Text = GlobalVar.userConfig.UploadInfo.url_DataUpload;
            tbx_url_GetDate.Text = GlobalVar.userConfig.UploadInfo.url_GetDate;
            tbx_url_GetModelInfo.Text = GlobalVar.userConfig.UploadInfo.url_GetModelInfo;
            tbx_url_DevStatusHead.Text = GlobalVar.userConfig.UploadInfo.url_DevStatusHead;
            tbx_DeviceName.Text = GlobalVar.userConfig.UploadInfo.url_DeviceName;
            if (GlobalVar.userConfig.cmdList==null)
            {
                GlobalVar.userConfig.cmdList = new List<Cmd>();
            }
            CmdListToTable(GlobalVar.userConfig.cmdList);
            #endregion
        }

        private void FormCamera_Load(object sender, EventArgs e)
        {
            if (GlobalVar.userConfig== null)
                GlobalVar.userConfig = new ConfigData();
            PameraToControl();
            this.rbn_ScanCamera.CheckedChanged += new System.EventHandler(this.rbn_ScanCamera_CheckedChanged);
            this.rbn_posCamera.CheckedChanged += new System.EventHandler(this.rbn_ScanCamera_CheckedChanged);
            this.rbn_plate1.CheckedChanged += new System.EventHandler(this.rbn_ScanCamera_CheckedChanged);
            rbn_ScanCamera_CheckedChanged(rbn_plate1, null);
            ConnectCamera();
            if (GlobalVar.IsFirstLoadConfig)
            {
                GlobalVar.IsFirstLoadConfig = false;
            
                uSerialPort1.Init();
                GlobalVar.Box1 = new BoxPort(uSerialPort1.spHelper.m_sp);
                GlobalVar.Box1.displayInfoMain += displalyInfo.displayInfoMainBox;
                uSerialPort2.Init();
                GlobalVar.Box2 = new BoxPort(uSerialPort2.spHelper.m_sp);
                GlobalVar.Box2.displayInfoMain+=displalyInfo.displayInfoMainBox;

                    uTCPIP2.tcpInit();
                    GlobalVar.mesTcp = new MesTCP(uTCPIP2.m_socketHelper);
                
                Task.Factory.StartNew(new Action(() =>
                {
                    while (!GlobalVar.isExit)
                    {
                        if (GlobalVar.userConfig.UploadInfo.IsUploadTcp)
                        {
                            if (GlobalVar.mesTcp.m_socket.tcp_client_connect)
                                break;
                            else
                            {
                                Application.DoEvents();
                                Thread.Sleep(9000);
                                this.BeginInvoke(new Action(() =>
                                {
                                    uTCPIP2.tcpInit();
                                    GlobalVar.mesTcp = new MesTCP(uTCPIP2.m_socketHelper);
                                }));
                            }
                        }
                        else
                            break;
                    }
                }));


                var plcList = new ContextMenuStrip();
                var zoomAdd = new ToolStripMenuItem("新增行");
                zoomAdd.Click += new System.EventHandler(this.dv_addRow_Click);
                plcList.Items.Add(zoomAdd);
                var zoomDelete = new ToolStripMenuItem("删除选中行");
                zoomDelete.Click += new System.EventHandler(this.dv_DeleteRow_Click);
                plcList.Items.Add(zoomDelete);
                dgv_camera_calib.ContextMenuStrip = plcList;

                var cmdList = new ContextMenuStrip();
                var cmdAdd = new ToolStripMenuItem("新增行");
                cmdAdd.Click += new System.EventHandler(this.cmd_addRow_Click);
                cmdList.Items.Add(cmdAdd);
                var cmdDelete = new ToolStripMenuItem("删除选中行");
                cmdDelete.Click += new System.EventHandler(this.cmd_DeleteRow_Click);
                cmdList.Items.Add(cmdDelete);

                dgv_cmd.ContextMenuStrip = cmdList;
            }

        }
        private void dv_addRow_Click(object sender, EventArgs e)
        {
            dgv_camera_calib.Rows.Add(new object[6] { dgv_camera_calib.Rows.Count+1, 0, 0, 0, 0,0 });
        }
        private void dv_DeleteRow_Click(object sender, EventArgs e)
        {
            if (dgv_camera_calib.SelectedRows.Count > 0)
            {
               if(DialogResult.Yes== MessageBox.Show("确定要删除选中行？","询问",MessageBoxButtons.YesNo))
                dgv_camera_calib.Rows.Remove(dgv_camera_calib.SelectedRows[0]);
            }
             
        }
        private void cmd_addRow_Click(object sender, EventArgs e)
        {
            dgv_cmd.Rows.Add(new object[2] { dgvc_action.Items[0].ToString(),"@|" });
        }
        private void cmd_DeleteRow_Click(object sender, EventArgs e)
        {
            if (dgv_cmd.SelectedRows.Count > 0)
            {
                if (DialogResult.Yes == MessageBox.Show("确定要删除选中行？", "询问", MessageBoxButtons.YesNo))
                    dgv_cmd.Rows.Remove(dgv_cmd.SelectedRows[0]);
            }

        }
        /// <summary>
        /// 将平台点显示到表格上
        /// </summary>
        /// <param name="lst"></param>
        private void CailPointToTable(List<CalibPoint>lst)
        {
            this.Invoke(new Action(()=> {
                dgv_camera_calib.Rows.Clear();
                if (lst != null)
                {
                    lst.OrderBy(a => a.Index).ToList().ForEach(a =>
                    {
                        dgv_camera_calib.Rows.Add(new object[6] { a.Index, a.pixX, a.pixY, a.realX, a.realY, a.realR });
                    });
                }
            }));
            
        }
        private void CmdListToTable(List<Cmd> lst)
        {
            dgv_cmd.Rows.Clear();
            if (lst != null)
            {
                lst.ToList().ForEach(a =>
                {
                    dgv_cmd.Rows.Add(new object[2] { a.action, a.cmd });
                });
            }
        }
        /// <summary>
        /// 切换平台
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbn_ScanCamera_CheckedChanged(object sender, EventArgs e)
        {
            var e_cur = GetCurrentSelet();
            var curVision = GlobalVar.userConfig.PlateVisionList[(int)e_cur];
            tbx_CameraSn.Text = curVision.Sn;
            if (curVision.CailList != null)
                CailPointToTable(curVision.CailList);
            nud_CenterXplate.Value = (decimal)curVision.CenterRealX;
            nud_CenterYplate.Value = (decimal)curVision.CenterRealY;
            nud_Xmax.Value = (decimal)curVision.Xmax;
            nud_Xmin.Value = (decimal)curVision.Xmin;
            nud_Ymax.Value = (decimal)curVision.Ymax;
            nud_Ymin.Value = (decimal)curVision.Ymin;
            nud_Rmax.Value = (decimal)curVision.Rmax;
            nud_Rmin.Value = (decimal)curVision.Rmin;
        }
        /// <summary>
        /// 连接相机
        /// </summary>
        /// <param name="pVision"></param>
        private void ConnectCamera()
        {
            HikVision cam = new HikVision(GlobalVar.userConfig.CameraSN_pos);
            if (cam.isInitSuccess)
            {
                cam.SetTriggerMode(TriggerMode.softTrigger);
                cam.StartGrab();
                cam.imageOut += visionProc.cam1;
                displalyInfo.displayInfoMain("定位相机连接成功");
       
            }
            GlobalVar.cameraList.Add(cam);
            HikVision camdraw = new HikVision(GlobalVar.userConfig.CameraSN_draw);
            if (camdraw.isInitSuccess)
            {
                camdraw.SetTriggerMode(TriggerMode.softTrigger);
                camdraw.StartGrab();
                camdraw.imageOut += visionProc.cam2;
                displalyInfo.displayInfoMain("图案相机连接成功");

            }
            GlobalVar.cameraList.Add(camdraw);
            HikVision cam_check = new HikVision(GlobalVar.userConfig.CameraSN_check);
            if (cam_check.isInitSuccess)
            {
                cam_check.SetTriggerMode(TriggerMode.softTrigger);
                cam_check.StartGrab();
                cam_check.imageOut += visionProc.cam3;
                displalyInfo.displayInfoMain("检测相机连接成功");
            }
            GlobalVar.cameraList.Add(cam_check);
        }

        private void btn_ConveyDown_Click(object sender, EventArgs e)
        {
            GlobalMotion.ConveryControrl(e_ConveryControl.下层输送启动, e_MachineStatus.无控制);
        }

        private void button29_Click(object sender, EventArgs e)
        {
            displalyInfo.displayInfoMain(((Button)sender).Text + "按钮按下");
            var arr_step=Enum.GetNames(typeof(e_Step_Label));
            var e_step = (e_Step_Label)Enum.Parse(typeof(e_Step_Label), ((Button)sender).Text);
            if (ckb_plate1.Checked&&ckb_plate2.Checked)
            {
                GlobalMotion.Step_Labeling(e_step, e_platePro.双平台有,e_MachineStatus.无控制);
            }else if(ckb_plate1.Checked)
            {
                GlobalMotion.Step_Labeling(e_step, e_platePro.平台1, e_MachineStatus.无控制);
            }
            else if (ckb_plate2.Checked)
            {
                GlobalMotion.Step_Labeling(e_step, e_platePro.平台2, e_MachineStatus.无控制);
            }
            else
            {
                MessageBox.Show("请选择平台");
            }

        }

       

        private void btn_Convery_Click(object sender, EventArgs e)
        {
            displalyInfo.displayInfoMain(((Button)sender).Text + "按钮按下");
            var arr_step = Enum.GetNames(typeof(e_Step_ConveryUp));
            var e_step = (e_Step_ConveryUp)Enum.Parse(typeof(e_Step_ConveryUp), ((Button)sender).Text);
            GlobalMotion.Step_ConveryUp(e_step, e_MachineStatus.无控制);
        }

        private void btn_Laser_Click(object sender, EventArgs e)
        {

        }

        private void btn_snap_Click(object sender, EventArgs e)
        {
            var curSelect = GetCurrentSelet();
            switch (curSelect)
            {
                case e_CameraPlate.定位相机平台1:
                case e_CameraPlate.定位相机平台2:
                    {
                        visionProc.curCameraPlate1 = curSelect;
                        GlobalVar.cameraList[(int)e_Camera.定位相机].softTrigger();
                    }
                    break;
                case e_CameraPlate.图案相机平台1:
                case e_CameraPlate.图案相机平台2:
                    {
                        visionProc.curCameraPlate2 = curSelect;
                        GlobalVar.cameraList[(int)e_Camera.图案相机].softTrigger();
                    }
                    break;
                case e_CameraPlate.检测相机平台1:
                case e_CameraPlate.检测相机平台2:
                    {
                        visionProc.curCameraPlate3 = curSelect;
                        GlobalVar.cameraList[(int)e_Camera.检测相机].softTrigger();
                    }
                    break;
            }
               
        }

        private void tabPage6_Click(object sender, EventArgs e)
        {

        }

        private void btn_ConveyDown_maual_Click(object sender, EventArgs e)
        {
            GlobalMotion.ConveryControrl(e_ConveryControl.下层输送停止, e_MachineStatus.无控制);
        }

        private void btn_ConveyStop_Click(object sender, EventArgs e)
        {
            GlobalMotion.ConveryControrl(e_ConveryControl.上层输送停止, e_MachineStatus.无控制);
        }

        private void btn_PixConvert_Click(object sender, EventArgs e)
        {
            var curSelect=GetCurrentSelet();
            var curVison = GlobalVar.userConfig.PlateVisionList[(int)curSelect];
            var curPos = new Postion() { Angle = (double)nud_c_pixR.Value, X = (double)nud_c_pixX.Value, Y = (double)nud_c_pixY.Value,
                xMax = curVison.Xmax, xMin = curVison.Xmin, yMax = curVison.Ymax, yMin = curVison.Ymin };
          
            var resPos1=visionProc.CalibratePostion(curPos, curVison, new PointF() { X = (float)curVison.CailPointX, Y = (float)curVison.CailPointY },GlobalVar.motionConfig.visionCenter1,GlobalVar.motionConfig.visionBase1);
            if( resPos1 != null)
            displalyInfo.displayInfoMain(JsonConvert.SerializeObject(resPos1));
        }

        private void btn_Move_scanX_Click(object sender, EventArgs e)
        {
            if (rbn_plate1.Checked)
                GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标X1下].PointMove((double)nud_pos_scanX.Value, true);
            else
                GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标X2上].PointMove((double)nud_pos_scanX.Value, true);
            displalyInfo.displayInfoMain(GetCurrentSelet().ToString()+ ((Button)sender).Text+ nud_pos_scanX.Value.ToString());
        }

        private void btn_Move_scanY_Click(object sender, EventArgs e)
        {
            GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标Y轴].PointMove((double)nud_pos_scanY.Value, true);
            displalyInfo.displayInfoMain(GetCurrentSelet().ToString() + ((Button)sender).Text+ nud_pos_scanY.Value.ToString());
        }

        private void btn_Move_scanR_Click(object sender, EventArgs e)
        {
            if (rbn_plate1.Checked)
                GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标R1下].PointMove((double)nud_pos_scanR.Value, true);
            else
                GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标R2上].PointMove((double)nud_pos_scanR.Value, true);
            displalyInfo.displayInfoMain(GetCurrentSelet().ToString() + ((Button)sender).Text + nud_pos_scanR.Value.ToString());
        }

        private void button46_Click(object sender, EventArgs e)
        {
            displalyInfo.displayInfoMain(((Button)sender).Text + "按钮按下");
            var arr_step = Enum.GetNames(typeof(e_Step_Cut));
            var e_step = (e_Step_Cut)Enum.Parse(typeof(e_Step_Cut), ((Button)sender).Text);
            if (ckb_pro1.Checked && ckb_pro2.Checked)
            {
                GlobalMotion.Step_Cut(e_step, e_platePro.双平台有,e_MachineStatus.无控制);
            }
            else if (ckb_pro1.Checked)
            {
                GlobalMotion.Step_Cut(e_step, e_platePro.平台1, e_MachineStatus.无控制);
            }
            else if (ckb_pro2.Checked)
            {
                GlobalMotion.Step_Cut(e_step, e_platePro.平台2, e_MachineStatus.无控制);
            }
            else
            {
                MessageBox.Show("请选择工装");
            }
        }

        private void btn_displayCrossing_Click(object sender, EventArgs e)
        {
            var curSelect = GetCurrentSelet();
            var cross= visionProc.DrawCrossing((double)nud_c_pixX.Value, (double)nud_c_pixY.Value, (double)nud_c_pixR.Value);
            switch (curSelect)
            {
                case e_CameraPlate.图案相机平台1:
                case e_CameraPlate.图案相机平台2:
                    GlobalVar.imageDisplay2_obj(cross, "yellow");
                    break;
                case e_CameraPlate.定位相机平台1:
                case e_CameraPlate.定位相机平台2:
                    GlobalVar.imageDisplay1_obj(cross, "yellow");
                    break;
                case e_CameraPlate.检测相机平台1:
                case e_CameraPlate.检测相机平台2:
                    GlobalVar.imageDisplay3_obj(cross, "yellow");
                    break;
            }
        }

        private void btn_addPoint_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgv_camera_calib.SelectedRows.Count > 0)
                {
                    if (rbn_plate1.Checked)
                    {
                        dgv_camera_calib.SelectedRows[0].Cells["dgvc_pixX"].Value = visionProc.Result1.dColumn.ToString("F03");
                        dgv_camera_calib.SelectedRows[0].Cells["dgvc_pixY"].Value = visionProc.Result1.dRow.ToString("F03");
                    }
                    else
                    {
                        dgv_camera_calib.SelectedRows[0].Cells["dgvc_pixX"].Value = visionProc.Result2.dColumn.ToString("F03");
                        dgv_camera_calib.SelectedRows[0].Cells["dgvc_pixY"].Value = visionProc.Result2.dRow.ToString("F03");
                    }
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain(ex.Message);
            }
        }

        private void btn_MoveScanZ_Click(object sender, EventArgs e)
        {

            GlobalMotion.Card_1.AxisList[(int)e_card1_axis.贴标Z轴].PointMove((double)nud_Move_scanZ.Value, true);

            displalyInfo.displayInfoMain(GetCurrentSelet().ToString() + ((Button)sender).Text + nud_Move_scanZ.Value.ToString());
        }

        private void btn_createDB_Click(object sender, EventArgs e)
        {
            
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
           var pros= GlobalVar.sqlHelper.selectFullTable<ProductInfo>(tbx_db_T_Product.Text);
            displalyInfo.displayInfoMain(JsonConvert.SerializeObject(pros));
        }

        private void btn_testInsert_Click(object sender, EventArgs e)
        {
            GlobalVar.sqlHelper.insert<ProductInfo>(tbx_db_T_Product.Text, new ProductInfo()
            {
                LabelTime = DateTime.Now,
                LaserTime = DateTime.Now,
                ProId = DateTime.Now.ToString("yyyyMMddHHmmssfff"),
                ProNo = 1,
                Result_down = e_Result.未知.ToString(),
                Result = e_Result.未知.ToString(),
                Result_up = e_Result.未知.ToString(),
                typeName = GlobalVar.closeSave.CurrentTypeName,
                
            }) ;
        }

        private void btn_queryAlarm_Click(object sender, EventArgs e)
        {
            var alarms = GlobalVar.sqlHelper.selectFullTable<AlarmInfo>(tbx_db_T_AlarmInfo.Text);
            displalyInfo.displayInfoMain(JsonConvert.SerializeObject(alarms));
        }

        private void btn_addAlarm_Click(object sender, EventArgs e)
        {
            GlobalVar.sqlHelper.insert<AlarmInfo>(tbx_db_T_AlarmInfo.Text, new AlarmInfo()
            {
               AlarmMsg="测试",
               startTime=DateTime.Now
            });
        }

        private void btn_createT_Alarm_Click(object sender, EventArgs e)
        {

        }

        private void btn_queryPro_Click(object sender, EventArgs e)
        {
            string querystr = "";
            string queryID = "";
            string queryResult = "";
            if (ckb_queryTime.Checked&& !string.IsNullOrEmpty(dtp_q_timeStart.Text))
            {
                querystr += $"LaserTime >'{dtp_q_timeStart.Text}' and LabelTime <'{dtp_q_timeEnd.Text}'";
            }
            if (ckb_queryID.Checked && !string.IsNullOrEmpty(tbx_q_Id.Text))
            {
                if(string.IsNullOrEmpty(querystr))
                  querystr += $"ProID ='{tbx_q_Id.Text}'";
                else
                  querystr += $"and ProID ='{tbx_q_Id.Text}'";
            }
            if (ckb_queryResult.Checked && !string.IsNullOrEmpty(cmb_q_result.Text))
            {
                if (string.IsNullOrEmpty(querystr))
                    querystr += $"Result ='like %{cmb_q_result.Text}'";
                else
                    querystr += $"and Result ='like %{cmb_q_result.Text}'";
            }
            if (!string.IsNullOrEmpty(querystr))
            {
                var lst = GlobalVar.sqlHelper.select<ProductInfo>(GlobalVar.userConfig.db_T_Product, querystr);
               
                dgv_display.Rows.Clear();
                if (lst != null)
                {
                    lst.ForEach(info =>
                    {
                        dgv_display.Rows.Add(info.ProId, info.ProNo, 
                            info.LaserTime == null ? "" : info.LaserTime?.ToString("yyyy-MM-dd HH:mm:ss"),
                            info.LabelTime == null ? "" : info.LabelTime?.ToString("yyyy-MM-dd HH:mm:ss"),
                            info.typeName, info.Result_up, info.Result_down, info.Result);
                    });
                    lst_pros = lst;
                }
             
            }
        }
        private List<ProductInfo> lst_pros;
        private void btn_exportPro_Click(object sender, EventArgs e)
        {
            if(dgv_display.Rows.Count>0&& lst_pros!=null&& lst_pros.Count>0)
            {
                FolderBrowserDialog dirDialog = new FolderBrowserDialog();
                dirDialog.Description = "请选择导出文件夹";
                if (dirDialog.ShowDialog() == DialogResult.OK)
                {
                    var dirPath = dirDialog.SelectedPath;
                    WriteCSV(lst_pros, dirPath);
                }
            }else
            {
                MessageBox.Show("请先查询生产数据");
            }
            
           
        }
        public void WriteCSV(List<ProductInfo> infoList,string dirPath)
        {
           
            string saveDate = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
            var strPath = dirPath + "\\" + saveDate + ".CSV";
            FileStream fs = new FileStream(strPath,FileMode.CreateNew);
            StreamWriter csvStreamWriter = new StreamWriter(fs,Encoding.Default);
            string strSpile = ",";
            csvStreamWriter.WriteLine($"平台号{strSpile}工装ID{strSpile}撕膜时间{strSpile}贴标时间{strSpile}生产配方{strSpile}上游结果{strSpile}下游结果{strSpile}结果{strSpile}撕膜结果{strSpile}贴标结果");
           
            infoList.ForEach(info=> {
                var tstr1 = info.LabelTime == null ? " " : info?.LabelTime?.ToString("yyyy-MM-dd HH:mm:ss");
                var tstr2 = info.LaserTime == null ? " " : info?.LaserTime?.ToString("yyyy-MM-dd HH:mm:ss");
                var str = info.ProNo.ToString() + strSpile + info.ProId + strSpile + tstr1 + strSpile + tstr2 + strSpile +
                  info.typeName + strSpile +
                  info.Result_up + strSpile +
                  info.Result_down + strSpile +
                  info.Result + strSpile + info.Result_Cut + strSpile + info.Result_Label;
                csvStreamWriter.WriteLine(str);
            });
            csvStreamWriter.Flush();
            csvStreamWriter.Close();
            fs.Close();
        }

        private void btn_status_Click(object sender, EventArgs e)
        {
            var res = UploadInterface.upload_DevStatusHead(e_Status.正常待机中,0,0,0);
            displalyInfo.displayInfoMain(JsonConvert.SerializeObject(res));
        }

        private void btn_alarm_Click(object sender, EventArgs e)
        {
            var res = UploadInterface.upload_AlarmUpload("测试报警上传");
            displalyInfo.displayInfoMain(JsonConvert.SerializeObject(res));
        }

        private void btn_check_Click(object sender, EventArgs e)
        {
            var res = UploadInterface.upload_CheckUpload("TestCampld");
            displalyInfo.displayInfoMain(JsonConvert.SerializeObject(res));

        }

        private void btn_model_Click(object sender, EventArgs e)
        {
            var res = UploadInterface.upload_GetModelInfo();
            displalyInfo.displayInfoMain(JsonConvert.SerializeObject(res));
        }

        private void btn_getDate_Click(object sender, EventArgs e)
        {
            var res = UploadInterface.upload_GetDate();
            displalyInfo.displayInfoMain(JsonConvert.SerializeObject(res));
        }

        private void btn_data_Click(object sender, EventArgs e)
        {
            var res = UploadInterface.upload_DataUpload(new ProductInfo()
            {
                AlarmTime = DateTime.Now,
                IsProcessAlarm = 0,
                LaserTime = DateTime.Now.AddSeconds(-6),
                LabelTime = DateTime.Now,
                ProId = "TestId",
                ProNo = 1,
                typeName = GlobalVar.closeSave.CurrentTypeName,
                Result = e_Result.出料NG.ToString(),
            });
            displalyInfo.displayInfoMain(JsonConvert.SerializeObject(res));
        }

        private void ckb_IsEnableUpSignal_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void btn_NG_conveyDistance_Click(object sender, EventArgs e)
        {
            GlobalMotion.Card_1.AxisList[(int)e_card1_axis.NG输送].ClearPos();
            GlobalMotion.Card_1.AxisList[(int)e_card1_axis.NG输送].PointMove((double)nud_NG_distance.Value, false);
        }

        private async void btn_Cail_Click(object sender, EventArgs e)
        {
            if (dgv_camera_calib.Rows == null || dgv_camera_calib.Rows.Count < 4)
            {
                MessageBox.Show("标定数据太少，请准备至少9个点数据");
                return;
            }
            if (DialogResult.No == MessageBox.Show($"确定要{((Button)sender).Text}吗?", "询问", MessageBoxButtons.YesNo))
                return;
            ((Button)sender).Enabled = false;
            await Task.Run(new Action(() => {
                var curSelect = GetCurrentSelet();
                var curVision = GlobalVar.userConfig.PlateVisionList[(int)curSelect];
                switch (curSelect)
                {
                    case e_CameraPlate.定位相机平台1:
                        if (curVision.CailList != null && curVision.CailList.Count >= 9)
                        {
                            var temp_cailArr = curVision.CailList.ToArray();
                            var isMoveOK = false;
                            visionProc.curCameraPlate1 = curSelect;
                            for (int i = 0; i < temp_cailArr.Length; i++)
                            {
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realX, (int)e_card1_axis.贴标X1下, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realY, (int)e_card1_axis.贴标Y轴, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realR, (int)e_card1_axis.贴标R1下, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                visionProc.Result1 = null;
                                GlobalVar.e_Camera_Pos1 = e_Camera_Pos.未拍照;
                                Thread.Sleep(GlobalVar.userConfig.delayCamera);
                                GlobalVar.cameraList[(int)e_Camera.定位相机].softTrigger();
                                isMoveOK = false;
                                Stopwatch sw = new Stopwatch();
                                sw.Restart();
                                while (true)
                                {
                                    Application.DoEvents();
                                    Thread.Sleep(2);
                                    if (visionProc.Result1 != null)
                                    {
                                        temp_cailArr[i].pixX = Convert.ToSingle(visionProc.Result1.dColumn.ToString("F03"));
                                        temp_cailArr[i].pixY = Convert.ToSingle(visionProc.Result1.dRow.ToString("F03"));
                                        isMoveOK = true;
                                        break;
                                    }
                                    if (sw.ElapsedMilliseconds > 3000)
                                    {
                                        break;
                                    }
                                }
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                {
                                    if (!isMoveOK)
                                    {
                                        displalyInfo.displayErrorMain("拍照定位NG,退出标定");
                                    }
                                    break;
                                }
                            }
                            if (isMoveOK && !GlobalVar.isEstop && !GlobalVar.isExit)
                            {
                                
                                CailPointToTable(temp_cailArr.ToList());

                                btn_calibrate_Click(btn_calibrate, null);

                            }
                        }
                        break;
                    case e_CameraPlate.定位相机平台2:
                        if (curVision.CailList != null && curVision.CailList.Count >= 9)
                        {
                            var temp_cailArr = curVision.CailList.ToArray();
                            var isMoveOK = false;
                            visionProc.curCameraPlate1 = curSelect;
                            for (int i = 0; i < temp_cailArr.Length; i++)
                            {
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realX, (int)e_card1_axis.贴标X2上, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realY, (int)e_card1_axis.贴标Y轴, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                isMoveOK = GlobalMotion.toPosition(temp_cailArr[i].realR, (int)e_card1_axis.贴标R2上, 1, true);
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                    break;
                                visionProc.Result2 = null;
                                GlobalVar.e_Camera_Pos2 = e_Camera_Pos.未拍照;
                                Thread.Sleep(GlobalVar.userConfig.delayCamera);
                                GlobalVar.cameraList[(int)e_Camera.定位相机].softTrigger();
                                isMoveOK = false;
                                Stopwatch sw = new Stopwatch();
                                sw.Restart();
                                while (true)
                                {
                                    Application.DoEvents();
                                    Thread.Sleep(2);
                                    if (visionProc.Result2 != null)
                                    {
                                        temp_cailArr[i].pixX = Convert.ToSingle(visionProc.Result2.dColumn.ToString("F03"));
                                        temp_cailArr[i].pixY = Convert.ToSingle(visionProc.Result2.dRow.ToString("F03"));
                                        isMoveOK = true;
                                        break;
                                    }
                                    if (sw.ElapsedMilliseconds > 3000)
                                    {
                                        break;
                                    }
                                }
                                if (!isMoveOK || GlobalVar.isEstop || GlobalVar.isExit)
                                {
                                    if (!isMoveOK)
                                    {
                                        displalyInfo.displayInfoMain("拍照定位NG,退出标定");
                                    }
                                    break;
                                }
                            }
                            if (isMoveOK && !GlobalVar.isEstop && !GlobalVar.isExit)
                            {
                                CailPointToTable(temp_cailArr.ToList());

                                btn_calibrate_Click(btn_calibrate, null);

                            }
                        }
                        break;
                }

            }));
            ((Button)sender).Enabled = true;
        }

        private void tabPage2_Click(object sender, EventArgs e)
        {

        }
    }
}
